package com.atguigu.day73_demo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @auther zzyy
 * @create 2024-08-02 21:29
 * 写线程首先获取写锁，更新数据，然后将锁降级为读锁。读线程在获取读锁后读取数据。
 * 这个过程演示了锁降级的概念，允许多个线程在持有读锁的情况下同时访问数据，
 * 提高了并发性能。`
 * 请注意，在锁降级期间，我们要确保数据的一致性，即在降级为读锁之前和之后都可以正确读取数据。
 * 这是锁降级的关键部分。（先获取读锁，再释放写锁）`
 */
class ClockDemote{
    private final ReentrantReadWriteLock readWriteLock=new ReentrantReadWriteLock();
   private  final Lock  readLock=readWriteLock.readLock();
   private  final  Lock WriteLock=readWriteLock.writeLock();
   int data=0;
   public int readData(){
       readLock.lock();
       try{
       return data;
       }finally{
             readLock.unlock();
        }
    }
   public  void updateData(Integer newData){
       WriteLock.lock();
       try{
    data=newData;
           System.out.println("更新或写入数据"+newData);
    readLock.lock();
    try{
int number=readData();
        System.out.println("Read number:"+number);
    }finally{
        WriteLock.unlock();
    }
    }finally{
          readLock.unlock();
     }
   }
}
public class LockDowngradingDemo {
    public static void main(String[] args) {
        ClockDemote clockDemote = new ClockDemote();
        new Thread(()->{
            clockDemote.updateData(42);
        }).start();

        new Thread(()->{
            int number=clockDemote.readData();
            System.out.println("Read get data"+number);
        }).start();
    }
}
